Passing a parameter by reference, which is what happens when you use the out
or ref
parameter modifiers, means that the
method will receive a pointer to the argument, rather than the argument itself. If the argument was a value type, the method will be able to change
the argument’s values. If it was a reference type, then the method receives a pointer to a pointer, which is usually not what was intended. Even when
it is what was intended, this is the sort of thing that’s difficult to get right, and should be used with caution.
This rule raises an issue when out
or ref
is used on a non-Optional
parameter in a public method.
Optional
parameters are covered by S3447.
Noncompliant code example
public void GetReply(
ref MyClass input, // Noncompliant
out string reply) // Noncompliant
{ ... }
Compliant solution
public string GetReply(MyClass input)
{ ... }
public bool TryGetReply(MyClass input, out string reply)
{ ... }
public ReplyData GetReply(MyClass input)
{ ... }
internal void GetReply(ref MyClass input, out string reply)
{ ... }
Exceptions
This rule will not raise issues for:
- non-public methods
- methods with only 'out' parameters, name starting with "Try" and return type bool.
- interface implementation methods